package com.whut.service.impl;

import com.whut.mapper.ProjectCheckMapper;
import com.whut.model.ProjectCheck;
import com.whut.service.ProjectCheckService;
import com.whut.tool.KeyUtil;
import com.whut.v_vo.ProjectCheckVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.stream.Collectors;


@Service("projectCheckService")
public class ProjectCheckServiceImpl implements ProjectCheckService {

    @Resource
    private ProjectCheckMapper projectCheckMapper;

    @Override
    public List<ProjectCheckVO> all() {
        return projectCheckMapper.findAll().stream().map(this::convertVO).collect(Collectors.toList());
    }

    @Override
    public ProjectCheck save(String name) {
        if (projectCheckMapper.findByName(name) != null) {
            throw new ArithmeticException("检查名称已存在");
        }
        ProjectCheck check = new ProjectCheck();
        check.setName(name);
        check.setSort(Long.valueOf(LocalDateTime.now().toEpochSecond(ZoneOffset.ofHours(8))).intValue());


        projectCheckMapper.save(check);

        return projectCheckMapper.findById(check.getId());
    }

    private ProjectCheckVO convertVO(ProjectCheck check) {
        ProjectCheckVO vo = new ProjectCheckVO();
        vo.setId(check.getId());
        vo.setKey(KeyUtil.transKey(check.getId()));
        vo.setName(check.getName());
        vo.setSort(check.getSort());
        return vo;
    }
}
